<template>
  <basic-container class="groupAnalysis">
    <div style="padding: 10px; text-align: right">
      <el-button type="primary" class="button" @click="handleDown"
        >导出分析报告</el-button
      >
    </div>
    <div id="groupAnalysisExport" style="width: 100%" v-if="loading">
      <div class="cover-div">
        <img class="cover" src="./img/团体报告封面JPG.jpg" alt="" />
        <div class="cover-title">
          <div>X</div>
          <div>X</div>
          <div>X</div>
          <div>X</div>
          <div>有</div>
          <div>限</div>
          <div>公</div>
          <div>司</div>
          <!-- 有限公司 -->
        </div>
        <div class="cover-date">{{ date }}</div>
      </div>

      <div class="content">
        <h3 class="textCenter">
          <!-- {{ demographicData.schoolName + demographicData.projectName }}研究报告 -->
          XXXX有限公司
        </h3>
        <h4 class="textCenter">心理健康发展报告</h4>
        <h3 class="textCenter">
          <span
            v-for="(item, count) in demographicData.gradeList"
            :key="count + new Date()"
          >
            <span>{{ item.name }}</span> </span
          >（{{ new Date(demographicData.createAt).getFullYear() }} 年）
        </h3>
        <div class="preface">
          任何一个个体或企业的成就与发展都离不开其优良的素质，所以当下的人员素质测评在任何一个个体或企业的成就与发展成为了必要性和肯能。员工发展始于清晰的自我认识。测评的目的之一是员工发展。而员工发展的出发点，很大程度上依赖于员工个人的自我认识。然而很多时候这种认识是有偏差的。在企业环境下，发展不是一件简单的自我完善的事情，需要自我完善加上适应公司的发展，很大程度上取决于双方。如公司的行为规范、对领导力的要求、职业生涯的规划等等。
        </div>
        <div class="preface">
          通过素质测评可以构建公司与个人发展的桥梁。HR在把公司的一些理念、价值观、领导力的要求，带到个体身上的时候，很大程度上是具体行为的一些体现。把公司的价值观和个人的行为联系起来，使员工能够从个体角度触摸到个人是什么样的。通过测评可以传递公司理念，给员工非常重要的帮助。
        </div>
        <div class="preface">
          素质测评是测试主题在较短时间内，采用科学的方法，收集被测评者在主要活动领域中的表征性，员工的素质测评是为了发掘、培养、开发及使用，使企业的核心竞争力得到更好的提升！企业通过员工测评从中分析有利于企业的规划和部署，为企业带来经济价值！同时企业可以实时掌握员工的素质状况，有助于企业进行员工的培训和发展！
        </div>
        <table border="1" class="table_style">
          <tbody>
            <tr>
              <td>企业名称</td>
              <td>XXXX有限公司</td>
            </tr>
            <tr>
              <td>数据采集时间</td>
              <td>{{ demographicData.createAt }}</td>
            </tr>
            <tr>
              <td>参加员工人数</td>
              <td>{{ sampleTotal }}</td>
            </tr>
          </tbody>
        </table>

        <br />
        <div
          style="
            background: burlywood;
            margin-top: 10px;
            margin-bottom: 10px;
            font-size: 20px;
            padding: 14px;
            color: white;
            text-align: center;
          "
        >
          心理健康
        </div>

        <br />
        <div>
          <h3>{{ demographicData.totalScoreMap[key].title }}</h3>
          <h3>测试目标：</h3>
          <div class="explain">
            本测验的目的是从感觉、情感、思维、意识、行为直到生活习惯、人际关系、饮食睡眠等多种角度，评定一个人是否有某种心理症状及其严重程度如何。它对有心理症状（即有可能处于心理障碍或心理障碍边缘）的人有良好的区分能力。适用于测查某人群中那些人可能有心理障碍，某人可能有何种心理障碍及其严重程度如何。不适合于躁狂症和精神分裂症。本测验不仅可以自我测查，也可以对他人（如其行为异常，有患精神或心理疾病的可能）进行核查，假如发现得分较高，则应进一步筛查。
          </div>
          <h3>量表适用：</h3>
          <div class="explain">本测验适用对象为16岁以上的人群。</div>
          <h3>测验说明：</h3>
          <div class="explain">{{ demographicData.remark }}</div>
          <h3>整体情况：</h3>
          <div>
            本次参与测评共计{{ demographicData.person }}，综合评估情况如下表：
            <div style="margin: 10px 0">
              <table border="1" class="table_style">
                <tbody>
                  <tr>
                    <td>正常</td>
                    <td>
                      {{ seriesData[0].value }}人，占比{{
                        parseFloat(
                          ((seriesData[0].value / count) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                    <td>需要关注</td>
                    <td>
                      {{ seriesData[5].value }}人，占比{{
                        parseFloat(
                          ((seriesData[5].value / count) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                  </tr>
                  <tr>
                    <td>重点预警</td>
                    <td>
                      {{ seriesData[4].value }}人；占比{{
                        parseFloat(
                          ((seriesData[4].value / count) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                    <td>一级预警</td>
                    <td>
                      {{ seriesData[1].value }}人，占比{{
                        parseFloat(
                          ((seriesData[1].value / count) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                  </tr>
                  <tr>
                    <td>二级预警</td>
                    <td>
                      {{ seriesData[2].value }}人，占比{{
                        parseFloat(
                          ((seriesData[2].value / count) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                    <td>三级预警</td>
                    <td>
                      {{ seriesData[3].value }}人，占比{{
                        parseFloat(
                          ((seriesData[3].value / count) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            具体结果如下图所示：
          </div>
          <div class="echarts1" id="heartWarningPie"></div>
          <div
            v-for="(item, index) in factorData.slice(0, 10)"
            :key="item.factorName"
          >
            <h4>{{ item.factorName }}</h4>
            <div class="explain">该因子主要是指{{ item.suggest }}</div>
            <div class="explain">{{ item.factorName }}调查结果如下所示:</div>
            <div style="margin: 10px 0">
              <table border="1" class="table_style">
                <tbody>
                  <tr>
                    <td>测评结果</td>
                    <td>正常</td>
                    <td>一般症状</td>
                    <td>严重症状</td>
                  </tr>
                  <tr>
                    <td>人数</td>
                    <td>{{ item.list[0].value }}</td>
                    <td>{{ item.list[1].value }}</td>
                    <td>{{ item.list[2].value }}</td>
                  </tr>
                  <tr>
                    <td>占比</td>
                    <td>
                      {{
                        parseFloat(
                          ((item.list[0].value / item.num) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                    <td>
                      {{
                        parseFloat(
                          ((item.list[1].value / item.num) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                    <td>
                      {{
                        parseFloat(
                          ((item.list[2].value / item.num) * 100).toFixed(2)
                        )
                      }}%
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div :id="'factor' + index" class="factor"></div>
          </div>
          <div>
            <h4>{{ factorData[factorData.length - 1].factorName }}</h4>
            <div class="explain">
              {{
                factorData[factorData.length - 1].factorName
              }}调查结果如下所示:
            </div>
            <div style="margin: 10px 0">
              <table border="1" class="table_style">
                <tbody>
                  <tr>
                    <td>测评结果</td>
                    <td>正常</td>
                    <td>需要关注</td>
                  </tr>
                  <tr>
                    <td>人数</td>
                    <td>
                      {{ factorData[factorData.length - 1].list[0].value }}
                    </td>
                    <td>
                      {{ factorData[factorData.length - 1].list[1].value }}
                    </td>
                  </tr>
                  <tr>
                    <td>占比</td>
                    <td>
                      {{
                        parseFloat(
                          (
                            (factorData[factorData.length - 1].list[0].value /
                              factorData[factorData.length - 1].num) *
                            100
                          ).toFixed(2)
                        )
                      }}%
                    </td>
                    <td>
                      {{
                        parseFloat(
                          (
                            (factorData[factorData.length - 1].list[1].value /
                              factorData[factorData.length - 1].num) *
                            100
                          ).toFixed(2)
                        )
                      }}%
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div :id="'factor' + (factorData.length - 1)" class="factor"></div>
          </div>
          <h3>XXXX公司总体心理健康分析：</h3>
          <div class="explain">
            调查显示，目前该企业员工的心理健康总体状况：有{{
              parseFloat(((seriesData[0].value / count) * 100).toFixed(2))
            }}%的员工心理健康正常， 在被调查的员工中有{{
              parseFloat(((seriesData[5].value / count) * 100).toFixed(2))
            }}%的员工心理健康是需要关注， 而有{{
              parseFloat(((seriesData[4].value / count) * 100).toFixed(2))
            }}%的员工是心理健康预警，
            由此可见，处于心理健康水平“需要关注”的员工，当前可能存在一些心理问题或心理困扰等情况，需要企业对他们进行进一步的心理辅导和心理健康教育。此外，对于处于心理“预警”的员工，其心理健康水平可能较低，甚至存在一定的心理疾病或心理障碍，需要立即对其进行面谈，了解其情绪状态，进而及时采取相应的预防措施。
            若Ta们的心理问题得不到及时解决，就可能会产生心理障碍或心理疾病
            ，此部分员工的心理问题不容忽视。
          </div>
          <h3>总结：</h3>
          <div class="explain">
            员工心理健康成长和发展从根本上来说是一种自觉和主动的过程，引导员工主动参与，切实提高心育实效，不断通过加大宣传力度，让员工科学了解发展性心理健康教育，强化其参与心理健康教育，从而优化自身心理素质，提高自身心理健康水平。
            心理健康教育工作是长期的、潜移默化的过程。企业承载着一份责任，一份希望。开展心理普及、建设心理室、建立每个员工的心理健康档案、制定个体辅导规划.....我们坚持着将每一次进步看做一个新的起点，站在这新的起点，把足迹延向远方，把心弦拨响，积蓄和迸发新的能量，让员工的心灵天空一片蔚蓝。
          </div>
        </div>
      </div>
      <div class="cover-div footer">
        <img class="cover2" src="./img/团体报告封底JPG.jpg" alt="" />
      </div>
    </div>
    <!-- <div style="text-align: center">
      <el-button type="primary" @click="handleDown">导出分析报告</el-button>
    </div> -->
  </basic-container>
</template>

<script>
import { getTeam } from "@/api/census/report";
import { mapGetters } from "vuex";
import { getList } from "@/api/census/grade";
import htmlToPdf from "@/util/htmlToPdf";
import * as echarts from "echarts";
import axios from "@/router/axios";
import { cloneDeep } from "lodash";
import { getList as getLevelList, getEducationInfo } from "@/api/system/dict";
import dayjs from "dayjs";
import { getTenantInfo } from "@/api/system/tenant";
export default {
  data() {
    return {
      form: {},
      activeNames: ["1"],
      totalScoreMapName: [],
      demographicData: [],
      conclusion: "",
      gradeServiceList: [],
      factorData: [],
      key: "",
      levelType: [
        { name: "正常", value: 0 },
        { name: "一般症状", value: 0 },
        { name: "严重症状", value: 0 },
      ],
      loading: false,
      seriesData: [],
      count: 0,
      date: "",
      sampleTotal: 0,
      educationInfo: {},
      tenantInfo: {},
      totalScoreMap: {},
    };
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: false,
        viewBtn: false,
        delBtn: true,
        editBtn: false,
      };
    },
  },
  created() {
    getList({}).then((res) => {
      this.gradeServiceList = res.data.data;
      this.getReportList();
    });
    this.date = dayjs(new Date()).format("YYYY年MM月DD日");
    this.sampleTotal = this.$route.query.sampleTotal;
    this.getSupervision();
  },
  methods: {
    getSupervision() {
      let info = JSON.parse(localStorage.getItem("saber-userInfo")).content;

      getTenantInfo(info.tenantId).then((res) => {
        this.tenantInfo = res.data.data;
      });
    },
    getGradeName(id) {
      for (let zz in this.gradeServiceList) {
        if (this.gradeServiceList[zz].gradeNo == id) {
          return this.gradeServiceList[zz].gradeName;
        }
      }
      return "";
    },
    getReportList() {
      getTeam(
        Object.assign({
          id: this.$route.query.id,
        })
      ).then(async (res) => {
        this.demographicData = res.data.data;
        // console.log(res.data.data);
        this.conclusion = this.demographicData.conclusion;
        for (var item in this.demographicData.totalScoreMap) {
          let rowData = this.demographicData.totalScoreMap[item];
          let sexTotalObj = {};
          rowData.sexTotal.map((vv) => {
            if (sexTotalObj[vv.factorName]) {
              sexTotalObj[vv.factorName].push(vv);
            } else {
              sexTotalObj[vv.factorName] = [vv];
            }
          });
          rowData.sexTotalObj = sexTotalObj;

          let gradeTotalObj = {};
          rowData.gradeTotal.sort(this.compare("other"));
          rowData.gradeTotal.map((vv) => {
            if (gradeTotalObj[vv.factorName]) {
              gradeTotalObj[vv.factorName].push(vv);
            } else {
              gradeTotalObj[vv.factorName] = [vv];
            }
          });
          rowData.gradeTotalObj = gradeTotalObj;
        }

        let key = Object.keys(res.data.data.totalScoreMap);
        this.key = key;
        let factorData = [];
        await axios
          .get(`/api/blade-measure/measure/gaugefactor/list`, {
            params: {
              current: 1,
              size: 20,
              gaugeId: key[0],
            },
          })
          .then((res) => {
            let data = res.data.data.records;
            data.forEach((item) => {
              if (
                item.factorName.indexOf("总分") == -1 &&
                item.factorName.indexOf("总均分") == -1
              ) {
                let factor = {
                  factorName: item.factorName,
                  suggest: item.suggest,
                  list: [],
                  num: 0,
                };
                this.demographicData.totalScoreMap[key].total.forEach(
                  (item2) => {
                    if (item.factorName == item2.factorName) {
                      let child = {};
                      if (item.factorName == "阳性项目数") {
                        child = {
                          name:
                            item2.name.indexOf("正常") > -1 ||
                            item2.name.indexOf("无需关注") > -1
                              ? "正常"
                              : "需要关注",
                          value: item2.num,
                        };
                        factor.num += item2.num;
                      } else {
                        child = {
                          name:
                            item2.name.indexOf("正常") > -1
                              ? "正常"
                              : item2.name.indexOf("一般症状") > -1
                              ? "一般症状"
                              : "严重症状",
                          value: item2.num,
                        };
                        factor.num += item2.num;
                      }

                      factor.list.push(child);
                    }
                  }
                );
                factorData.push(factor);
              }
            });

            this.factorData = cloneDeep(factorData);
            // console.log(factorData);

            this.factorData.map((item) => {
              let levelType = {};
              if (item.factorName == "阳性项目数") {
                levelType = [
                  { name: "正常", value: 0 },
                  { name: "需要关注", value: 0 },
                ];
              } else {
                levelType = [
                  { name: "正常", value: 0 },
                  { name: "一般症状", value: 0 },
                  { name: "严重症状", value: 0 },
                ];
              }

              let data = levelType.map((item2) => {
                item.list.map((item3) => {
                  if (item2.name == item3.name) {
                    item2.value = item3.value;
                  }
                });
                return item2;
              });
              item.list = data;
              return item;
            });
            this.$nextTick(() => {
              // this.initChartData();
              this.initWarning(this.factorData);
            });
          });
      });
    },
    handleDown() {
      this.$loading({
        lock: true,
        text: "正在导出报告...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      htmlToPdf.downloadPDF(
        document.querySelector("#groupAnalysisExport"),
        this.demographicData.schoolName + "团体分析报告",
        this
      );
    },
    compare(property) {
      return function (a, b) {
        var value1 = a[property] * 1;
        var value2 = b[property] * 1;
        return value1 - value2;
      };
    },
    async initWarning(factorData) {
      this.getCount(this.demographicData.projectId, factorData);
    },
    initWholeEcharts(seriesData) {
      var chartDom = document.getElementById("heartWarningPie");
      var myChart = echarts.init(chartDom);
      var option;
      option = {
        legendHoverLink: false,
        grid: {
          height: 180,
        },
        title: {
          text: "整体测评概况",
          textStyle: {
            color: "#0986b3",
            fontSize: 18,
          },
          x: "center",
          y: "bottom",
        },
        tooltip: {
          trigger: "item",
          showContent: true,
          // formatter: "{a}<br />{b}: {c}人(占比：{d}%)",
          formatter: "{b}: {c}人(占比：{d}%)",
          textStyle: {
            fontSize: 16,
          },
        },
        legend: {
          orient: "horizontal",
          top: "87%",
          textStyle: {
            // color: "white",
            fontSize: 16,
          },
        },
        color: ["green", "#FF4500", "#FFA07A", "#FFD700", "#8552a1", "#224b8f"],
        series: [
          {
            name: "心理安全预警",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["50%", "45%"],
            data: seriesData,
            labelLine: {
              length: 8,
              length2: 7,
              show: true,
            },
            label: {
              // position: "inside",
              // color: "white",
              formatter: "{d}%",
              textStyle: {
                fontSize: 16,
              },
            },
          },
        ],
      };

      option && myChart.setOption(option);
    },
    initFactorEachrts(seriesData, index) {
      var chartDom = document.getElementById("factor" + index);
      var title = seriesData.factorName + "测评情况";
      var myChart = echarts.init(chartDom);
      var option;
      option = {
        legendHoverLink: false,
        grid: {
          height: 260,
        },
        title: {
          text: title,
          textStyle: {
            color: "#0986b3",
            fontSize: 18,
          },
          x: "center",
          y: "bottom",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a}<br />{b}: {c}人(占比：{d}%)",
        },
        legend: {
          orient: "horizontal",
          top: "87%",
          textStyle: {
            color: "#0986b3",
            fontSize: 16,
          },
        },
        color: ["green", "#FFA07A", "#FF4500", "#FFD700", "#224b8f", "#8552a1"],
        series: [
          {
            name: "心理安全预警",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["50%", "45%"],
            data: seriesData.list,
            label: {
              formatter: "{c} 人",
              textStyle: {
                fontSize: 16,
              },
            },
          },
        ],
      };

      option && myChart.setOption(option);
    },
    async getCount(projectId, factorData) {
      let seriesData = [];
      await getLevelList(1, 1000, { code: "warning_level" }).then((res) => {
        res.data.data[0].children.map((vv) => {
          if (vv.dictKey != 0) {
            seriesData.push(vv);
          }
        });
        seriesData.unshift({
          dictKey: 0,
          dictValue: "正常人数",
        });
        seriesData = seriesData.map((item) => {
          let level = {
            code: item.dictKey,
            name: item.dictValue,
            value: 0,
          };
          return level;
        });
        axios
          .get("/api/blade-measure/measure/userprojectgauge/count", {
            params: {
              projectId,
            },
          })
          .then((res) => {
            let data = res.data.data;
            let num = 0;
            seriesData.map((item) => {
              data.map((item2) => {
                if (item.code == item2.level) {
                  item.value = item2.count;
                }
              });
              return item;
            });
            seriesData.forEach((item) => {
              num += item.value;
            });
            this.seriesData = seriesData;
            this.count = num;
            this.loading = true;

            this.$nextTick(() => {
              this.initWholeEcharts(seriesData);
              factorData.forEach((item, index) => {
                this.initFactorEachrts(item, index);
              });
            });

            // console.log(res.data);
            // console.log(seriesData);
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
* {
  font-size: 23px !important;
}
.button {
  font-size: 16px !important;
}

.wordWrapClass {
  word-wrap: break-word; /*英文的时候需要加上这句，自动换行*/
  /*自测了这句话没啥用*/
  writing-mode: vertical-rl; /*从左向右 从右向左是 writing-mode: vertical-rl;*/
  writing-mode: tb-rl; /*IE浏览器的从左向右 从右向左是 writing-mode: tb-rl；*/
  text-align: center;
  padding: 0px;
  display: flex;
  -webkit-display: flex;
  flex-direction: column;
  /* align-content: center; */
  /* vertical-align: middle; */
  justify-content: center;
}
.cover-div {
  position: relative;
  padding: 0 50px 0 60px;

  .cover {
    width: 100%;
    height: 1430px;
  }

  .cover2 {
    width: 100%;
    height: 1430px;
  }

  .cover-title {
    position: absolute;
    left: 280px;
    top: 721px;
    // -webkit-writing-mode: vertical-rl;
    // writing-mode: vertical-rl;
    font-size: 40px !important;
    font-weight: bold;
    color: rgb(0, 161, 153);
    width: 70px;
    // word-wrap: break-word;

    span {
      font-size: 45px !important;
      line-height: 45px;
      padding-left: 10px;
    }

    div {
      margin: 0 auto;
      font-size: 40px !important;
      text-align: center;
      line-height: 40px;
    }
  }

  .cover-date {
    position: absolute;
    right: 70px;
    bottom: 28px;
    font-size: 30px !important;
    font-weight: bold;
  }
}

.footer {
  // margin-top: 50px;
}
.groupAnalysis {
  #groupAnalysisExport {
    background-color: #fff;
    width: 1090px !important;
    /* height: 400px; */
    margin: auto;
    padding: 40px;
    box-sizing: border-box;
  }
  .textCenter {
    text-align: center;
  }
  .margin40 {
    margin: 40px;
  }
  .table_style td,
  th {
    padding: 10px;
    font-size: 15px;
    max-width: 300px;
  }
  .textCenter {
    text-align: center;
  }
  .table_style {
    border-collapse: collapse;
    width: 100%;
    text-align: center;
  }
  .collapseTitle {
    font-size: 15px;
    font-weight: 900;
  }

  h3 {
    font-size: 28px !important;
  }
}

.content {
  padding: 0px 50px 0 60px;
}

.explain {
  text-indent: 46px;
}

.echarts1 {
  // width: 350px;
  height: 480px;
  margin: 0 auto;
}

.factor {
  // width: 300px;
  height: 480px;
  margin: 0 auto;
}

.preface {
  margin: 10px 0;
  text-indent: 46px;
  line-height: 35px;
}
</style>
